package com.example.schoolmgt.controller;

import com.example.schoolmgt.model.School;
import com.example.schoolmgt.service.SchoolService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.net.URISyntaxException;
import java.util.List;

@RestController
public class SchoolController {
    private final static Logger log = LoggerFactory.getLogger(SchoolController.class);
    @Resource
    private SchoolService schoolService;

    @GetMapping("/ping")
    public String ping() {
        log.info("ping");
        return "pong";
    }

    @GetMapping("/queryAll")
    public List<School> queryAll() {
        log.info("queryAll");
        List<School> lists = schoolService.queryAll();
        return lists;
    }

    @PostMapping("/school")
    public School school() {
        log.info("create a school");
        try {
            return schoolService.create();
        } catch (Exception e) {
            log.error("create school,course,teacher failed: {}", e.getMessage());
            return school();
        }
    }

    @GetMapping("/findSchoolById")
    public School findSchoolById(@RequestParam Long id) {
        try {
            log.info("find school by id");
            School school = schoolService.findSchoolById(id);
            return school;
        } catch (Exception e) {
            log.error("find school failed: " + id);
            return null;
        }
    }

    @GetMapping("/cachedSchoolById")
    public School cachedSchoolById(@RequestParam Long id) {
        try {
            log.info("find cached school by id");
            School school = schoolService.cachedSchoolById(id);
            return school;
        } catch (Exception e) {
            log.error("find cached school failed: " + id);
            return null;
        }
    }

    @PostMapping("/updateSchool")
    public String updateSchool(@RequestBody School school) {
        log.info("updateSchool");
        int result = schoolService.updateSchool(school);
        if (result != 0) {
            return "update school success";
        }
        log.error("update school failed");
        return "failed";
    }

    @DeleteMapping("/deleteSchoolById")
    public String deleteSchoolById(@RequestParam Long id) {
        log.info("delete school by id");
        int result = schoolService.deleteSchoolById(id);
        if (result != 0) {
            return "delete success";
        }
        log.error("delete school failed");
        return "delete failed";
    }
}
